package main

import (
	"errors"
	"fmt"
)

func main() {
	fmt.Println(ErrCodeTest)               //code:200
	fmt.Printf("%T\n", ErrCodeTest)        //*errors.errorString
	fmt.Printf("%T\n", ErrDbConnectFailed) //*errors.errorString
	fmt.Println(getDbInfo())
	updateDb()
	
	//errorTest()
}

var (
	ErrDbConnectFailed = errors.New("数据库连接失败")
	ErrDbUsernameError = errors.New("数据库用户名错误")
	ErrDbPasswordError = errors.New("数据库密码错误")
	ErrCodeTest        = fmt.Errorf("code:%d", 200)
)

// 判断具体的错误类型再处理相关逻辑
func updateDb() {
	err := checkDbConnect()
	if err != nil {
		switch err {
		case ErrDbConnectFailed:
			fmt.Println("处理数据库连接失败的逻辑...")
			return
		case ErrDbUsernameError:
			fmt.Println("处理数据库用户名错误的逻辑...")
			return
		case ErrDbPasswordError:
			fmt.Println("处理数据库密码错误的逻辑...")
			return
		}
	}
	fmt.Println("操作处理完成")
}

func getDbInfo() (string, error) {
	err := checkDbConnect()
	if err != nil { //此处不关心返回错误值携带的具体上下文信息，只要发生错误就返回
		return "", err
	}
	return "mysql", nil
}

func checkDbConnect() error {
	foo := false
	if !foo {
		return ErrDbConnectFailed
	}
	return nil
}

func errorTest() {
	err := errors.New("your first demo error")
	fmt.Println("err错误:", err)
}
